
import axios from 'axios';
import { getAccessToken } from '@/utils/auth'

const service = axios.create({
  timeout: 120000,
  baseURL: process.env.VUE_APP_BASE_API
  // withCredentials: true, // 跨域时携带cookies
})

service.interceptors.request.use(
  async config => {
    // 防止缓存，给get请求加上时间戳
    if (config.method === 'get') {
      const url = config.url
      url.indexOf('?') === -1 ? config.url = url + '?_=' + (new Date().getTime()) : config.url = url + '&_=' + (new Date().getTime())
    }
    const token = getAccessToken('token') 
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  err => Promise.reject(err)
)

service.interceptors.response.use(
  response => {
    return response.data
  },
  async error => {
    // console.log(error.response);
    switch (error.response.status) {
      case 500: // 接口异常
      case 502: // 接口异常
      case 504: // 接口异常
        console.log('接口异常');
        // Message({ message: '接口异常，请稍后重试',  type: 'error'})
        break
      case 401: // token过期 重新登录
        console.log('跳转登录页');
        break
      default:
        console.log('err' + error)
    }
    return Promise.reject(error)
  }
)
export default service